const express = require("express");
const Result = require('../models/Result')
const article = require('../web_services/article');
const memberUser = require('../services/memberUser');
const  homeServices  = require('../services/home');
const { md5 , decoded ,checkMobile } = require("../utils");
const { PWD_SALT , PRIVATE_KEY , USER_JWT_EXPIRED } = require("../utils/constant");
const jwt = require("jsonwebtoken")
const Boom = require('boom');
const { validationResult } = require("express-validator")

const router = express.Router();

Date.prototype.Format = function (fmt) { // author: meizz
	var o = {
		"M+": this.getMonth() + 1, // 月份
		"d+": this.getDate(), // 日
		"h+": this.getHours(), // 小时
		"m+": this.getMinutes(), // 分
		"s+": this.getSeconds(), // 秒
		"q+": Math.floor((this.getMonth() + 3) / 3), // 季度
		"S": this.getMilliseconds() // 毫秒
	};
	if (/(y+)/.test(fmt))
		fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
	for (var k in o)
		if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
		return fmt;
}

router.post('/addArticle',function(req,res,next){//发布文章
    let data = req.body
	if(data.content==''){
        new Result(null,'文章内容不能为空').fail(res)
		return;
    }
	if(data.category_id==''){
        new Result(null,'请选择分类').fail(res)
		return;
    }
	const decode = decoded(req)
	if(decode && decode.uid){
		data.uid = decode.uid
		data.state = 1
		var aid = data.id
		data.updated_at = new Date().Format("yyyy-MM-dd hh:mm:ss")
		if(data.id!=''){//编辑
			if(data.isTemplate=='1'){//如果选择了模板就执行
				delete data.isTemplate;
				if(data.template_id!=''){//编辑模板
					delete data.template_name;
					article.updateTemplate(data).then(list=>{//保存模板
				
					})
				}else{
					delete data.template_id;
					delete data.state;
					console.log("保存模板",data)
					article.addTemplate(data).then(list=>{//保存模板
				
					})
				}
				delete data.template_name;
				delete data.template_id;
				data.state = 1
				data.id = aid
				article.updataArticle(data).then(list=>{
					new Result({
						id:data.id
					},'编辑成功').success(res)
				})
			}else{
				delete data.template_name;
				delete data.isTemplate;	
				delete data.template_id;

				article.updataArticle(data).then(list=>{
					new Result({
						id:data.id
					},'编辑成功').success(res)
				})
			}
		}else{//新增
			if(data.id==''){
				delete data.id;
			}
			if(data.isTemplate=='1'){//如果选择了模板就执行
				delete data.isTemplate;
				
				if(data.template_id!=''){//编辑模板
					delete data.state;
					delete data.template_name;
					article.updateTemplate(data).then(list=>{//保存模板
				
					})
				}else{
					delete data.state;
					delete data.template_id;
					article.addTemplate(data).then(list=>{//保存模板
				
					})
				}
				delete data.template_name;
				delete data.template_id;
				delete data.id;
				article.addArticle(data).then(list=>{
					new Result({
						id:list.insertId
					},'新增成功').success(res)
				})
			}else{
				delete data.template_name;
				delete data.isTemplate;	
				delete data.template_id;

				article.addArticle(data).then(list=>{
					new Result({
						id:list.insertId
					},'新增成功').success(res)
				})
			}
		}
	}
})

router.post('/getArticleList',function(req,res,next){//获取帖子列表
	let data = req.body	
	article.getArticleList(data).then(list=>{
		new Result(list,'查询成功').success(res)
	})

	
})

router.post('/getMyArticleList',function(req,res,next){//获取我的帖子列表
	let data = req.body
	const decode = decoded(req)
	if(decode && decode.uid){
		data.id = decode.uid
		article.getMyArticleList(data).then(list=>{
			new Result(list,'查询成功').success(res)
		})
	}
})

router.post('/getUserArticleList',function(req,res,next){//获取用户帖子列表
	let data = req.body
	article.getUserArticleList(data).then(list=>{
		new Result(list,'查询成功').success(res)
	})
	
})




router.post('/getSearchArticleList',function(req,res,next){//获取搜索帖子列表
	let data = req.body	
	article.getSearchArticleList(data).then(list=>{
		new Result(list,'查询成功').success(res)
	})
})




router.post('/getArticle',function(req,res,next){//获取文章详情
	let data = req.body
	
	const decode = decoded(req) || false
	
	if(decode && decode.uid){
		data.uid = decode.uid
		article.getArticle(data).then(list=>{
			if(decode.uid == list.uid){
				list.is_my = '1'
			}
			if(data.type==1){
				new Result(list,'查询成功').success(res)
			}else{
				article.updateHistory({//增加足迹
					aid:data.id,
					uid:data.uid,
					updated_at:new Date().Format("yyyy-MM-dd hh:mm:ss"),
				}).then(data2=>{
					
				})
				article.updataArticle({//增加阅读量
					id:data.id,
					reading_number:list.reading_number+=1
				}).then(data2=>{
					new Result(list,'查询成功').success(res)
				})	
			}
			
		})
		
	}else{
		article.getArticle(data).then(list=>{
			if(data.type==1){
				new Result(list,'查询成功').success(res)
			}else{
				article.updataArticle({
					id:data.id,
					reading_number:list.reading_number+=1
				}).then(data2=>{
					list.relation_type='0'
					list.is_collect='0'
					new Result(list,'查询成功').success(res)
				})	
			}
			
		})
	}
})





router.post('/getArticleState',function(req,res,next){//获取文章状态
	let data = req.body
	const decode = decoded(req)
	if(decode && decode.uid){
		article.getArticle(data).then(list=>{
			if(list.state==1){
				new Result({
					state:1,
					title:'发布成功',
					suptitle:'审核中，即将发布，请耐心等待。'
				},'查询成功').success(res)
			}
		})
	}
})


router.post('/getArticleReject',function(req,res,next){//查询驳回原因
	let data = req.body
	const decode = decoded(req)
	if(decode && decode.uid){
		article.getArticleReject(data).then(list=>{
			new Result(list,'查询成功').success(res)
		})
	}
})


router.post(//删除文章
    '/removeArticle',
    function(req,res){
        const decode = decoded(req)
        if(decode && decode.uid){
            article.removeArticle(req.body).then(data=>{
                new Result(null,'删除成功').success(res)
            })
        }
    }
)

router.post(//删除模板
    '/removeTemplate',
    function(req,res){
        const decode = decoded(req)
        if(decode && decode.uid){
            article.removeTemplate(req.body).then(data=>{
                new Result(null,'删除成功').success(res)
            })
        }
    }
)



router.get('/getCategoryList',function(req,res,next){//获取分类
	article.getCategoryList().then(list=>{
		new Result(list,'查询成功').success(res)
	})
})



router.get('/getTemplate',function(req,res,next){//获取模板
	const decode = decoded(req)
	let data = req.body
	if(decode && decode.uid){
		data.uid = decode.uid
		article.getTemplate(data).then(list=>{
			new Result(list,'查询成功').success(res)
		})
	}
})

router.post('/updateTemplate',function(req,res,next){//更新用户模板
	let data = req.body
	const decode = decoded(req)
	if(decode && decode.uid){
		data.uid = decode.uid
		article.updateTemplate(data).then(list=>{
			new Result(null,'更新成功').success(res)

		}).catch(err=>{
            next(Boom.badImplementation(err))
        })
	}
})

router.post('/updateCollect',function(req,res,next){//更新收藏
	let data = req.body
	const decode = decoded(req)
	if(decode && decode.uid){
		data.uid = decode.uid
		article.updateCollect(data).then(list=>{
			new Result(null,'更新成功').success(res)

		}).catch(err=>{
            next(Boom.badImplementation(err))
        })
	}
})



router.post('/getMyCollect',function(req,res,next){//获取我的收藏列表
	let data = req.body
	const decode = decoded(req)
	if(decode && decode.uid){
		data.uid = decode.uid
		article.getMyCollect(data).then(list=>{
			new Result(list,'查询成功').success(res)
		})
	}
})

router.post('/getMyHistory',function(req,res,next){//获取我的收藏列表
	let data = req.body
	const decode = decoded(req)
	if(decode && decode.uid){
		data.uid = decode.uid
		article.getMyHistory(data).then(list=>{
			new Result(list,'查询成功').success(res)
		})
	}
})


router.post('/setArticleTop',function(req,res,next){//设置置顶
	let data = req.body
	const decode = decoded(req)
	if(data.aid==''){
        new Result(null,'id不能为空').fail(res)
		return;
    }
	if(data.end_time==''){
        new Result(null,'天数不能为空').fail(res)
		return;
    }
	if(!isInteger(data.end_time)){	
		new Result(null,'请输入正确的天数格式').fail(res)
		return;
	}
	if(decode && decode.uid){
		memberUser.isUser(decode.uid,'uid').then(user=>{
            if(user){
				homeServices.getConfiguration().then(config=>{
					var needMoney = Number(data.end_time) * Number(config.isTop_money)
					if(user.balance<needMoney){
						new Result(null,'您的余额不足,请充值').fail(res)
						return;
					}else{
						memberUser.updataUser({
							id:decode.uid,
							balance:user.balance-needMoney
						}).then(user2=>{
							article.setTopArticle({
								id:data.aid,
								isTop:1,
								end_time:data.end_time
							}).then(list=>{
								new Result(list,'置顶成功').success(res)
							}).catch(err=>{
								new Result(null,'置顶失败').fail(err)
							})
						})
					}
				})
            }else{
                new Result('用户信息查询失败').fail(res)
            }
        })
	}
})


function addDate(days){
	if(days == undefined || days == '') {
		days = 1;
	}
	var date = new Date();
	date.setDate(date.getDate() + days);
	var month = date.getMonth() + 1;
	var day = date.getDate();
	var hours = date.getHours();
	var minutes = date.getMinutes();
	var mm = "'" + month + "'";
	var dd = "'" + day + "'";
	//单位数前面加0
	if(mm.length == 3) {
		month = "0" + month;
	}
	if(dd.length == 3) {
		day = "0" + day;
	}
	var time = date.getFullYear() + "-" + month + "-" + day+ " " + hours + ":" + minutes;
	return time;
}

function isInteger(obj) {
	return obj%1 === 0
}




module.exports = router